# 采集本机信息 执行命令
import subprocess
import requests
import paramiko
import json
'''
agent模式，每台服务器都要有脚本
subprocess
'''
def agent():
    v1 = subprocess.getoutput('ipconfig')
    v1 = v1[20:30]
    print(v1)

    # 拿到之后发送数据
    v2 = subprocess.getoutput('dir')
    v2 = v2[2:12]
    print (v2)

    # 发送请求
    url = 'http://127.0.0.1:8000/asset/'
    info = {'k1':{'ens33':'中文'},'k2':{'ens33':'xxx'}}
    response = requests.post(
        url=url,
        #data={'k1':{'ens33':'xxx'},'k2':{'ens33':'xxx'}}
        # json={'k1':{'ens33':'中文'},'k2':{'ens33':'xxx'}}
        data = json.dumps(info).encode('utf-8')

    )
    print(response.text)
'''
ssh 放在中控机 一份
paramiko
'''
# def ssh():
#     # 创建ssh对象
#     ssh = paramiko.SSHClient()
#     # 允许连接不在know_hosts文件中的主机,可以不要
#     # ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#     #连接服务器
#     ssh.connect(hostname='10.25.135.70',port=22,username='root',password='123.com' )
#     # 执行命令
#     stdin, stdout, stderr = ssh.exec_command('ls')
#     # 获取命令结果
#     result = stdout.read()
#     # 关闭连接
#     ssh.close()
############################################
def ssh():
    url = 'http://127.0.0.1:8000/api/asset/'
    response = requests.get(url=url,)
    # ret = response.text
    ret = response.json()
    print(ret,type(ret))



'''
salt(中控机)
'''
# # def salt():
# #     import salt.client
# #     local = salt.client.LocalClient()
# #     result = local.cmd('192.168.12.21','cmd.run',['ifconfig'])
# #
mode = 'ssh'
if mode == 'agent':
    agent()
elif mode == 'ssh':
    ssh()
# elif mode == 'salt':
#     salt()

